//
//  RecordTool.m
//  cascade-realm
//
//  Created by QSC on 3/6/24.
//

#import "RecordTool.h"
#import <AVFoundation/AVFoundation.h>
@interface RecordTool()
@property(nonatomic,strong)AVAudioRecorder * recorder;

@property(nonatomic,strong)AVPlayer * player;
@property (nonatomic,copy)void(^playFinishBlock)(void);
@end
@implementation RecordTool

static RecordTool *_tool = nil;
+ (instancetype)shared {
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _tool = [[RecordTool alloc]init];
    });
    return _tool;
}


+ (void)ready{
    
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
    
    [[AVAudioSession sharedInstance] setActive:YES error:nil];
    
    [[AVAudioSession sharedInstance] setPreferredIOBufferDuration:0.005 error:nil];
    
    [[AVAudioSession sharedInstance] setPreferredSampleRate:44100 error:nil];
}

+ (void)startRecord{
    
    [RecordTool ready];
    
    NSString * path = [RecordTool getVoicePath];
    
    [RecordTool shared].path = path;
    
    NSURL * url = [NSURL fileURLWithPath:path];
    
    NSDictionary *recordSetting = [[NSDictionary alloc] initWithObjectsAndKeys:
                                   //采样率  8000/11025/22050/44100/96000（影响音频的质量）
                                   [NSNumber numberWithFloat: 44100.0],AVSampleRateKey,
                                   // 音频格式
                                   [NSNumber numberWithInt: kAudioFormatMPEG4AAC],AVFormatIDKey,
                                 
                                   // 音频通道数 1 或 2
                                   [NSNumber numberWithInt: 1], AVNumberOfChannelsKey,
                                   //录音质量
                                   [NSNumber numberWithInt:AVAudioQualityHigh],AVEncoderAudioQualityKey,
                                   nil];
    AVAudioRecorder * recorder =  [[AVAudioRecorder alloc] initWithURL:url settings:recordSetting error:nil];
    recorder.meteringEnabled = YES;
    [recorder prepareToRecord];
    [recorder record];
    [recorder updateMeters];
    
    [RecordTool shared].recorder = recorder;
    

    
}

+ (void)stopRecord{
    
    
    [RecordTool shared].recordTime = [RecordTool shared].recorder.currentTime;
    
    [[RecordTool shared].recorder stop];
    

    [RecordTool shared].recorder = nil;
    
}


+ (NSString *)getVoicePath{
    
    NSString * time = [NSString stringWithFormat:@"%.0f",[[NSDate date] timeIntervalSince1970]];
    
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.m4a",time]];
    
    return  path;
}


- (void)playUrl:(NSURL *)url finishBlock:(void(^)(void))playFinishBlock{
    
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
    
    if (![[NSFileManager defaultManager] fileExistsAtPath:url.path]) {
        return;
    }
    
    if (self.player.timeControlStatus == AVPlayerTimeControlStatusPlaying) {
        [self.player pause];
        return;
    }

    AVPlayerItem * item = [[AVPlayerItem alloc] initWithURL:url];
    self.player = [AVPlayer playerWithPlayerItem:item];
    [self.player play];
    self.playFinishBlock = playFinishBlock;
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(PlayDidEnd) name:AVPlayerItemDidPlayToEndTimeNotification object:item];

    
}

- (void)stopPlay{
   
    [self.player pause];
    [self.player replaceCurrentItemWithPlayerItem:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    self.player = nil;
}

- (void)PlayDidEnd{
    if(self.playFinishBlock){
        self.playFinishBlock();
    }
}
@end
